package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override//新增
    public void save1(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    @Override
    public PageResult<Clazz> page(String name, LocalDate begin, LocalDate end, Integer page, Integer pageSize) {
        // 1. 创建 MyBatis-Plus 的分页对象，明确指定泛型类型
        IPage<Clazz> pageObj = new Page<>(page, pageSize);

        // 2. 构造查询条件
        QueryWrapper<Clazz> queryWrapper = new QueryWrapper<>();
        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("name", name);
        }
        if (begin != null && end != null) {
            queryWrapper.between("create_time", begin, end);
        }

        // 3. 执行分页查询
        IPage<Clazz> resultPage = clazzMapper.selectPage(pageObj, queryWrapper);

        // 4. 封装结果，确保 PageResult 构造函数参数类型匹配
        return new PageResult<>(resultPage.getTotal(), resultPage.getRecords());
    }

    @Override//查询
    public Clazz getInfo(Integer id) {
        return this.getById(id);
    }

    @Override//修改
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        updateById(clazz);
    }

    @Override
    public void deleteById(Integer id) {
        //1. 查询班级下是否有学员
        Integer count = studentMapper.countByClazzId(id);
        if(count > 0){
            throw new BusinessException("班级下有学员, 不能直接删除~");
        }
        //2. 如果没有, 再删除班级信息
        removeById(id);
    }

    @Override
    public List<Clazz> findAll() {
        return list();
    }
}